package com.sky.loveshop.controller;

import cn.hutool.json.JSONUtil;
import com.sky.loveshop.entity.Result;
import com.sky.loveshop.entity.Shop;
import com.sky.loveshop.entity.common.PageResult;
import com.sky.loveshop.entity.exception.BizException;
import com.sky.loveshop.entity.exception.BizExceptionEnum;
import com.sky.loveshop.entity.qo.ShopQO;
import com.sky.loveshop.service.ShopService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.sql.DataSource;
import javax.validation.Valid;
import java.sql.SQLException;
import java.util.Date;
import java.util.List;

/**
 * @author xcy
 * @version V1.0
 * @description
 * @date 2024/8/18 0:04
 */
@Slf4j
@RestController
@RequestMapping("/shop")
public class ShopController {

    @Autowired
    private ShopService shopService;

    @PostMapping("/listShopPages")
    public Result<PageResult<Shop>> listShopPages(@RequestBody ShopQO shopQO) {
        return Result.page(shopService.listShopPages(shopQO));
    }

    @PostMapping("/listShop")
    public Result<List<Shop>> listShop(@RequestBody ShopQO shopQO) {
        return Result.success(shopService.listShop(shopQO));
    }

    @PutMapping("/addShop")
    public Result<Integer> addShop(@RequestBody @Valid Shop shop) {
        shop.setCreateTime(new Date());
        log.info("addShopParam = {}", JSONUtil.toJsonStr(shop));
        return Result.success(shopService.addShop(shop));
    }

    @DeleteMapping("/delShopById")
    public Result<Integer> delShopById(Integer id) throws BizException {
        if (id == null) {
            throw new BizException(BizExceptionEnum.ID_MUST_NEED);
        }
        return Result.success(shopService.delShopById(id));
    }

    @PostMapping("/editShop")
    public Result<Integer> editShop(@RequestBody Shop shop) throws BizException {
        log.info("editShopParam = {}", JSONUtil.toJsonStr(shop));
        if (shop.getId() == null) {
            throw new BizException(BizExceptionEnum.ID_MUST_NEED);
        }
        return Result.success(shopService.updateShopById(shop));
    }

    @GetMapping("/getShopById")
    public Result<Shop> getShopById(Integer id) throws BizException {
        if (id == null) {
            throw new BizException(BizExceptionEnum.ID_MUST_NEED);
        }
        return Result.success(shopService.getShopById(id));
    }

    /**
     * 测试一下Hikari连接池是否连上
     */
    @Autowired
    private DataSource dataSource;
    @GetMapping("test")
    public void testHikari() throws SQLException {
        System.out.println("dataSource = " + dataSource);
        System.out.println("dataSource connection = " + dataSource.getConnection().getClass());
    }

}
